package com.xiaomi.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.sun.deploy.net.URLEncoder;
import com.xiaomi.pojo.User;
import com.xiaomi.service.AddressService;
import com.xiaomi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;

/**
 * @ClassName UserServlet
 * @Description TODO
 * @Author xiao宋
 * @Date 16:37  2022/9/13
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    AddressService addressService;

    /**
     * 注销登录功能
     */
    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session) {
        session.invalidate();
        return "redirect:/login.jsp";
    }
    /**
     * 注册账号功能
     */
    @RequestMapping("/register")
    public String register(User user) {
//        user.setEmail(req.getParameter("email"));
//        user.setGender(req.getParameter("gender"));
//        user.setPassword(req.getParameter("password"));
//        user.setUsername(req.getParameter("username"));

        boolean register = userService.register(user);
        System.out.println(user);
        if (register) {
            return "redirect:/adminLogin";
        } else {
            System.out.println("用户：" + user + "注册失败");
            return "redirect:/register";
        }
    }
    /**
     * 校验验证码
     */
    @RequestMapping("/checkCode")
    public void checkCode(String code, HttpSession session, HttpServletResponse resp) throws Exception {
//      系统随机到的验证码。
        String realCap = (String) session.getAttribute("captcha");
        System.out.println("用户输入的验证码" + code);
        System.out.println("系统随机到的验证码" + realCap);
        PrintWriter writer = resp.getWriter();
        if (code == null || code.length() == 0) {
//            return "1";
            writer.write("1");
        } else {
            if (realCap.equalsIgnoreCase(code)) {
//                return "0";
                writer.write("0");
            } else {
                System.out.println("验证码校验失败");
//                return "1";
                writer.write("1");
            }
        }
    }
    /**
     * 校验用户名是否存在
     * @ResponseBody
     */
    @ResponseBody
    @RequestMapping("/checkUserName")
    public void checkUserName(String username, HttpServletResponse resp) throws Exception {
        System.out.println("校验用户名方法-> 从前端接收到的user名字：" + username);
        /**
         * StringUtils.isEmpty()
         * 判断是否为空的方法
         */
        PrintWriter writer = resp.getWriter();
        if (StringUtils.isEmpty(username)) {
            writer.write("0");
//            mv.addAttribute("data",0);
//            return "0";
        } else {
            User findname = userService.findByUsername(username);
            System.out.println("数据库查到的username:" + findname);

            if (findname == null) {
                writer.write("2");
//                return "2";
            } else {
                writer.write("1");
//                return "1";
            }
        }
    }
    /**
     * 登录
     */
    @RequestMapping("/login")
    public String login(String username, String password, String auto, HttpSession session) throws Exception {
        //判断是否自动登录的
        User user = userService.findByUserAndPwd(username, password);
        System.out.println("登录处通过名字密码查到的数据：" + user);
        if (user == null) {
            System.out.println("登录login方法。查到的user为空");
            return "redirect:/login.jsp";
        } else {
            //保存到session里
            session.setAttribute("user", user);
            if ("on".equalsIgnoreCase(auto)) {

                String encode = URLEncoder.encode(username + "#" + password, "utf-8");

                Cookie cookie = new Cookie("user", encode);
                //设置域名
                cookie.setDomain("localhost");
                //任意路径下都可以获取cookie
                cookie.setPath("/");
                //设置有效期为两周
                cookie.setMaxAge(14 * 24 * 60 * 60);
//              resp.addCookie(cookie);
            }
            return "redirect:/index.jsp";
        }
    }

//**********************************************************************************************
//**********************************************************************************************

//      后台系统

//**********************************************************************************************
//**********************************************************************************************

    /**
     * 后台系统登录
     * @return
     * @throws Exception
     */
    @RequestMapping("/adminLogin")
    public String adminLogin(String username, String password, HttpSession session) {
        User user = userService.findByUserAndPwd(username, password);
        //如果查到不是空的，就是用户真实，
        if (user != null) {
            //有数据就写到session里是已经登录成功了
            session.setAttribute("admin", user);
        } else {
            return "redirect:/admin/login.jsp";
        }
        return "redirect:/admin/admin.jsp";
    }
    /**
     * 显示所有会员信息
     * @param resp
     * @return tb_user
     */
    @RequestMapping("/adminGetUserList")
    public void getUserList(HttpServletResponse resp) throws Exception {
        // flag 1 会员 0管理员 2无效会员
        List<User> list = userService.gerUserList();
        resp.setCharacterEncoding("utf-8");
        //转成json
        String data = JSON.toJSONString(list);
        resp.getWriter().write(data);
    }
    /**
     * 获得所有的无效会员。 --> flag== 2
     * @param resp
     * @throws Exception
     */
    @RequestMapping("/adminGetInvalidList")
    public void getInvalidList(HttpServletResponse resp) throws Exception {
        List<User> list = userService.gerInvaldUser();
        resp.setCharacterEncoding("utf-8");
        //转成json
        String data = JSON.toJSONString(list);
        resp.getWriter().write(data);
    }
    /**
     * 删除 用户，通过 ID
     */
    @RequestMapping("/adminDeleteUser")
    public void deleteUser(String id, HttpServletResponse resp) throws Exception {
        System.out.println(id);
        userService.deleteUserById(id);
        getUserList(resp);
    }
    /**
     * 查找会员用户和普通。通过名字+性别
     */
    @ResponseBody
    @RequestMapping("/adminSearchUser")
    public List searchUser(String username, String gender) {
        List<User> userList = userService.getUserByName(username, gender, 0);
        System.out.println("前端传过来的名字： " + username + "前端传过来的性别： " + gender);
//            resp.setCharacterEncoding("utf-8");
        //转成json
//            String data = JSON.toJSONString(userList);
        if (userList != null || userList.size() != 0) {
//                resp.getWriter().write("没找到");
            return userList;
        } else {
//                resp.getWriter().write(data);
            return null;
        }
    }
    /**
     * 查找失效用户
     */
    @ResponseBody
    @RequestMapping("/adminSearchUserInvalid")
    public List<User> searchUserInvalid(String username, String gender ){
        List<User> userList = userService.getUserByName(username, gender, 1);
//        resp.setCharacterEncoding("utf-8");
        //转成json
//        String data = JSON.toJSONString(userList);
        if (userList == null||userList.size()==0) {
//            resp.getWriter().write("没找到");
            return null;
        } else {
//            resp.getWriter().write(data);
        return userList;
        }
    }
}